﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using OnlineVideos.ViewModels;
using OnlineVideos.Common;
using Common.Library;
using Microsoft.Phone.Controls;
using OnlineVideos.View_Models;
using System.ComponentModel;
using OnlineVideos.Data;
using Common.Utilities;
using OnlineVideos.UI;
using OnlineVideos.Entities;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using FlurryWP8SDK.Models;
using System.Windows.Controls.Primitives;
namespace OnlineVideos
{
    public partial class ShowChapters : UserControl
    {
        ShowDetail detailModel;
        private bool IsDataLoaded;
        ObservableCollection<ShowLinks> objChapterList;
        public ShowChapters()
        {
            InitializeComponent();
            objChapterList = new ObservableCollection<ShowLinks>();
            detailModel = new ShowDetail();
            IsDataLoaded = false;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
               
                if (IsDataLoaded == false)
                {
                    GetPageDataInBackground();
                    IsDataLoaded = true;
                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in UserControl_Loaded method In ShowChapters.cs file.", ex);
            }
        }

        private void GetPageDataInBackground()
        {
            try
            {
                BackgroundHelper bwHelper = new BackgroundHelper();

                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {

                                                a.Result = OnlineShow.GetShowLinksByType(AppSettings.ShowID, LinkType.Movies/*, false*/);
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {

                                                objChapterList = (ObservableCollection<ShowLinks>)a.Result;
                                                if (objChapterList.Count > 0)
                                                {
                                                    lbxChapterLinks.ItemsSource = objChapterList;
                                                    tblkFavNoMovies.Visibility = Visibility.Collapsed;

                                                }
                                                else
                                                {
                                                    lbxChapterLinks.ItemsSource = null;
                                                    tblkFavNoMovies.Text = "No " + AppResources.ShowDetailPageChaptersPivotTitle + " available";
                                                    tblkFavNoMovies.Visibility = Visibility.Visible;
                                                }

                                            }
                                          );

                bwHelper.RunBackgroundWorkers();

            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in GetPageDataInBackground method In ShowChapters.cs file.", ex);
            }
        }

        private void lbxChapterLinks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (lbxChapterLinks.SelectedIndex == -1)
                    return;
                AppSettings.LinkType = (lbxChapterLinks.SelectedItem as ShowLinks).LinkType.ToString();
                AppSettings.LinkTitle = (lbxChapterLinks.SelectedItem as ShowLinks).Title.ToString();
                
                var selecteditem1 = (sender as Selector).SelectedItem as ShowLinks;
                var Itemcollection = (sender as ListBox).Items.ToList();
                Constants.YoutubePlayList = new Dictionary<string, string>();
                foreach (var item in Itemcollection.Cast<ShowLinks>().Where(i => i.LinkOrder > selecteditem1.LinkOrder))
                {
                    if (!Constants.YoutubePlayList.ContainsKey(item.LinkUrl))
                    Constants.YoutubePlayList.Add(item.LinkUrl, item.Title);
                }
                foreach (var item in Itemcollection.Cast<ShowLinks>().Where(i => i.LinkOrder < selecteditem1.LinkOrder))
                {
                    if (!Constants.YoutubePlayList.ContainsKey(item.LinkUrl))
                    Constants.YoutubePlayList.Add(item.LinkUrl, item.Title);
                }
                History objHistory = new History();
                objHistory.SaveMovieHistory((lbxChapterLinks.SelectedItem as ShowLinks).ShowID.ToString(), (lbxChapterLinks.SelectedItem as ShowLinks).Title);
              
              
                if (ResourceHelper.AppName == Apps.Indian_Cinema_Pro.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Story_Time_Pro.ToString())
                AppSettings.startplayingforpro = true;
                else
                    AppSettings.startplaying = true;
                AppSettings.PlayVideoTitle = Constants.YoutubePlayList.FirstOrDefault().Value;
                //YoutubeApi.Youtube.PlayYoutubeVideo((lbxChapterLinks.SelectedItem as ShowLinks).LinkUrl);
                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                Page p = frame.Content as Page;
                p.NavigationService.Navigate(new Uri("/Views/Youtube.xaml?myid=" + (lbxChapterLinks.SelectedItem as ShowLinks).LinkUrl, UriKind.Relative));
                lbxChapterLinks.SelectedIndex = -1;
                lbxChapterLinks.IsEnabled = false;
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in lbxChapterLinks_SelectionChanged method In ShowChapters.cs file.", ex);
            }
        }
      
       
        private void btnBrokenMovie_Click(object sender, RoutedEventArgs e)
        {
            detailModel.ReportBrokenLink(lbxChapterLinks, sender as MenuItem);
        }
        private async void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem menu = sender as MenuItem;
                ListBoxItem selectedListBoxItem = lbxChapterLinks.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                int showid = (selectedListBoxItem.Content as ShowLinks).ShowID;
                int linkid = (selectedListBoxItem.Content as ShowLinks).LinkID;
                string linktype = (selectedListBoxItem.Content as ShowLinks).LinkType;
                var xquery = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(id => id.ShowID == showid && id.LinkID == linkid && id.LinkType == linktype).FirstOrDefaultAsync()).Result;
                if (xquery != null)
                {
                    if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                    {
                        await Constants.connection.DeleteAsync(xquery);
                    }
                }
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in MenuItem_Click_1 method In ShowChapters.cs file.", ex);
            }
        }

        private void ContextMenu_Opened_1(object sender, RoutedEventArgs e)
        {
            try
            {
                ContextMenu menu = sender as ContextMenu;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                int showid = AppSettings.ShowUniqueID;
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                {

                    var item = menu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                    item.IsEnabled = true;
                }
                else
                {
                    var item = menu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                    item.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_1 method In ShowChapters.cs file.", ex);
            }

        }
       
    }
}
